package com.zxg.zbc.biz.util.jwt;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

public class TokenUtils {

	public static String getToken(Long userId) {
		String token = "";
		Map<String, Object> payload = new HashMap<String, Object>();
		Date date = new Date();
		payload.put("uid", userId + "");// 用户id
		payload.put("iat", date.getTime());// 生成时间:当前
		payload.put("ext", date.getTime() + 2000 * 60 * 60);// 过期时间2小时
		token = Jwt.createToken(payload);
		return token;
	}

	public static Long getUserIdFromToken(String token) {
		Map<String, Object> resultMap = Jwt.validToken(token);
		if (StringUtils.equals((String) resultMap.get("state"), TokenState.VALID.getState())) {
			@SuppressWarnings("unchecked")
			HashMap<String, String> dataobj = (HashMap<String, String>) resultMap.get("data");
			String userId = dataobj.get("uid");
			return Long.parseLong(userId);
		}
		return 0L;
	}

	public static void main(String[] args) {
		System.out.println(getToken(10086L));
		System.out.println(getUserIdFromToken(
				"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHQiOjE0Nzc2NDMzMzAzMTAsInVpZCI6IjEwMDg2IiwiaWF0IjoxNDc3NjM2MTMwMzEwfQ.gR3xca9S-RimIZLDp9SNyg2q3Hjs0NK7uAnWnwJOMRI"));
	}
}
